package com.easidea.tim.service.purchase;

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springside.core.service.EntityService;

import com.easidea.tim.dao.base.FlowNoDao;
import com.easidea.tim.dao.commodity.ProductDao;
import com.easidea.tim.dao.inventory.StorageDao;
import com.easidea.tim.dao.purchase.PurchaseReturnDao;
import com.easidea.tim.dao.purchase.PurchaseReturnItemDao;
import com.easidea.tim.dao.supply.SupDao;
import com.easidea.tim.dao.system.orgnization.StaffDAO;
import com.easidea.tim.entity.commodity.Product;
import com.easidea.tim.entity.purchase.PurchaseReturn;
import com.easidea.tim.entity.purchase.PurchaseReturnItem;
import com.easidea.tim.entity.supply.Sup;
import com.easidea.tim.util.DateUtil;
import com.easidea.tim.util.Page;
import com.easidea.tim.util.TimConstant.FlowNoType;

public class PurchaseReturnService extends
		EntityService<PurchaseReturn, PurchaseReturnDao> {

	private PurchaseReturnDao purchaseReturnDao;

	private PurchaseReturnItemDao purchaseReturnItemDao;

	private SupDao supDao;

	private ProductDao productDao;

	private FlowNoDao flowNoDao;

	private StaffDAO staffDao;

	private StorageDao storageDao;

	/**
	 * 分页获取销售订单列表
	 * 
	 * @param page
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Page getPurchaseReturnListByCondition(String creator,
			String saleOrderNum, String suppName, Date startTime, Date endTime, Page page, String status) {
		Criteria ca = createPurchaseReturnListByConditionCriteria(creator,
				saleOrderNum, suppName, startTime, endTime, status);
		ca.setProjection(Projections.count("id"));
		Integer totalNum = (Integer) ca.uniqueResult();
		Criteria ca1 = createPurchaseReturnListByConditionCriteria(creator,
				saleOrderNum, suppName, startTime, endTime, status);
		int startIndex = Page.getStartOfPage(page.getCurrentPageNo(), page
				.getPageSize());
		ca1.setFirstResult(startIndex);
		ca1.setMaxResults(page.getPageSize());
		List<PurchaseReturn> ls = (List<PurchaseReturn>) ca1.list();
		Page resultPage = new Page(startIndex, totalNum, page.getPageSize(), ls);
		resultPage.setCurrentPageNo(page.getCurrentPageNo());

		return resultPage;

	}

	@SuppressWarnings("unchecked")
	public Page getPurchaseReturnListByCreator(String creator,
			String saleOrderNum, String suppName, Date startTime, Date endTime,
			Page page, String status) {
		Criteria ca = createPurchaseReturnListByConditionCriteria(creator,
				saleOrderNum, suppName, startTime, endTime, status);
		ca.setProjection(Projections.count("id"));
		Integer totalNum = (Integer) ca.uniqueResult();
		Criteria ca1 = createPurchaseReturnListByCreatorCriteria(creator,
				saleOrderNum, suppName, startTime, endTime, status);
		int startIndex = Page.getStartOfPage(page.getCurrentPageNo(), page
				.getPageSize());
		ca1.setFirstResult(startIndex);
		ca1.setMaxResults(page.getPageSize());
		List<PurchaseReturn> ls = (List<PurchaseReturn>) ca1.list();
		Page resultPage = new Page(startIndex, totalNum, page.getPageSize(), ls);
		resultPage.setCurrentPageNo(page.getCurrentPageNo());

		return resultPage;

	}

	@SuppressWarnings( { "unused", "deprecation", "unchecked" })
	private Criteria createPurchaseReturnListByCreatorCriteria(String creator,
			String saleOrderNum, String suppName, Date startTime, Date endTime,String status) {
		Criteria ca = createUnDeletedCriteria();
		String[] array = null;
		String narray = "";
		 if (creator != null && !creator.equals("")) {
			ca.add(Restrictions.ilike("creator", creator, MatchMode.ANYWHERE));
		}


		if (saleOrderNum != null && !saleOrderNum.equals("")) {
			ca.add(Restrictions.ilike("purchaseReturnNum", saleOrderNum,
					MatchMode.ANYWHERE));
		}

		if (status != null && !status.equals("")) {
			ca.add(Restrictions.eq("status", new Integer(status).shortValue()));
		}
		if (suppName != null && !suppName.equals("")) {
			ca.createAlias("sup", "sup");
			ca
					.add(Restrictions.ilike("sup.name", suppName,
							MatchMode.ANYWHERE));
		}

		if (startTime != null && !startTime.equals("") && endTime != null
				&& !endTime.equals("")) {
			ca.add(Restrictions.between("modifyTime", DateUtil
					.getStartTime(startTime), DateUtil.getEndTime(endTime)));
		}

		ca.addOrder(Order.desc("modifyTime"));
		return ca;
	}

	@SuppressWarnings( { "unused", "deprecation", "unchecked" })
	private Criteria createPurchaseReturnListByConditionCriteria(
			String creator, String saleOrderNum, String supName,
			Date startTime, Date endTime, String status) {
		Criteria ca = createUnDeletedCriteria();
		String[] array = null;
		String narray = "";

		if (creator != null && !creator.equals("")) {
			ca.add(Restrictions.ilike("creator", creator, MatchMode.ANYWHERE));
		}

		if (saleOrderNum != null && !saleOrderNum.equals("")) {
			ca.add(Restrictions.ilike("purchaseReturnNum", saleOrderNum,
					MatchMode.ANYWHERE));
		}

		if (status != null && !status.equals("")) {
			ca.add(Restrictions.eq("status", new Integer(status).shortValue()));
		}
		if (supName != null && !supName.equals("")) {
			ca.createAlias("sup", "sup");
			ca.add(Restrictions.ilike("suo.name", supName, MatchMode.ANYWHERE));
		}

		if (startTime != null && !startTime.equals("") && endTime != null
				&& !endTime.equals("")) {
			ca.add(Restrictions.between("modifyTime", DateUtil
					.getStartTime(startTime), DateUtil.getEndTime(endTime)));
		}

		ca.addOrder(Order.desc("modifyTime"));
		return ca;
	}

	@SuppressWarnings("unchecked")
	public List<PurchaseReturn> GetPurchaseReturnList(String creator,
			String saleOrderNum, String supName, Date startTime, Date endTime,
			String orderType, String status) {
		Criteria ca = this.createPurchaseReturnListByConditionCriteria(creator,
				saleOrderNum, supName, startTime, endTime, status);
		return ca.list();
	}

	/**
	 * 新增或修改时获取初始化数据列表（客户列表）
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Sup> getInitDataList() {
		return supDao.GetAllSupplier();

	}

	public List<Product> getAllProducts() {
		return this.productDao.getAllValid();
	}

	/**
	 * 保存订单
	 * 
	 * @param saleOrder
	 * @param items
	 * @return
	 */
	public boolean savePurchaseReturn(PurchaseReturn purchaseReturn,
			List<PurchaseReturnItem> items) {
		String flowNo = "";
		double moneyNum = 0;
		double meterNum = 0;
		double piNum = 0;
		for (PurchaseReturnItem item : items) {

			meterNum = meterNum
					+ Double.valueOf(item.getTotalMeter()).doubleValue();
			moneyNum = moneyNum
					+ (Double.valueOf(item.getTotalMeter()).doubleValue() * item
							.getUnitPrice());
			piNum = piNum + item.getPiNum();
		}
		flowNo = this.flowNoDao.genNextFlowNo(FlowNoType.PURCHASE_RETURN);
		purchaseReturn.setCreateTime(new Date());
		purchaseReturn.setMoneyNum(moneyNum);
		purchaseReturn.setMeterNum(meterNum);
		purchaseReturn.setPiNum(piNum);
		purchaseReturn.setPurchaseReturnNum(flowNo);
		purchaseReturn.setId(null);

		purchaseReturn.setFlowNo(flowNo);
		// saleOrder.setCreator(saleOrder.getCustomer().getStaff().getName());
		this.purchaseReturnDao.save(purchaseReturn);

		for (PurchaseReturnItem item : items) {
			Product product = productDao.getProductByColorAndName(item
					.getProductName(), item.getProductColor());
			item.setId(null);
			item.setProduct(product);
			item.setPurchaseReturn(purchaseReturn);
			this.purchaseReturnItemDao.save(item);
			// DueFromSummary summary = saveDueFromSummary(saleOrder);
			// this.saveDueFrom(summary, saleOrder);
		}

		return true;
	}

	/**
	 * 修改订单数据
	 * 
	 * @param saleOrder
	 * @param items
	 * @return
	 */
	public boolean updatePurchaseReturn(PurchaseReturn purchaseReturn,
			List<PurchaseReturnItem> items) {
		double moneyNum = 0;
		double meterNum = 0;
		double piNum = 0;
		PurchaseReturn purchaseReturnTmp = this.get(purchaseReturn.getId());

		for (PurchaseReturnItem item : items) {

			meterNum = meterNum
					+ Double.valueOf(item.getTotalMeter()).doubleValue();
			moneyNum = moneyNum
					+ (Double.valueOf(item.getTotalMeter()).doubleValue() * item
							.getUnitPrice());
			piNum = piNum + item.getPiNum();
		}
		purchaseReturnTmp.setModifyTime(new Date());
		purchaseReturnTmp.setMoneyNum(moneyNum);
		purchaseReturnTmp.setMeterNum(meterNum);
		purchaseReturnTmp.setReAddress(purchaseReturn.getReAddress());
		purchaseReturnTmp.setReTel(purchaseReturn.getReTel());
		purchaseReturnTmp.setRePerson(purchaseReturn.getRePerson());
		purchaseReturnTmp.setMemo(purchaseReturn.getMemo());
		// saleOrder.setPiNum(piNum * returnflag);
		purchaseReturnTmp.setPiNum(piNum);
		purchaseReturnTmp.setStatus(new Integer(0).shortValue());
		this.storageDao.cancelChargedStorageByFlowNo(purchaseReturnTmp
				.getFlowNo());

		this.purchaseReturnItemDao.deleteItemsByOrderId(purchaseReturn.getId());

		for (PurchaseReturnItem item : items) {

			item.setMeterNum("0");
			Product product = productDao.getProductByColorAndName(item
					.getProductName(), item.getProductColor());
			double pi = item.getPiNum();
			item.setPiNum(pi);
			item.setId(null);
			item.setProduct(product);
			item.setPurchaseReturn(purchaseReturnTmp);
			this.purchaseReturnItemDao.save(item);
			// DueFromSummary summary = saveDueFromSummary(purchaseReturn);
			// this.saveDueFrom(summary, purchaseReturn);
		}
		this.purchaseReturnDao.merge(purchaseReturnTmp);
		return true;
	}


	/**
	 * 填充销售订单
	 * 
	 * @param dto
	 * @param items
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public boolean CompleteUpdate(PurchaseReturn purchaseReturn,
			List<PurchaseReturnItem> items) {
		double moneyNum = 0;
		double meterNum = 0;
		double piNum = 0;
		this.purchaseReturnItemDao.deleteItemsByOrderId(purchaseReturn.getId());
		String array[] = null;

		for (PurchaseReturnItem item : items) {
			item.setPurchaseReturn(purchaseReturn);
			array = item.getMeterNum().split(",");
			double total = 0;
			for (int i = 0; i < array.length; i++) {
				total = total + Double.parseDouble(array[i]);
			}

			piNum = piNum + item.getPiNum();
			meterNum = meterNum + total;
			moneyNum = moneyNum + (total * item.getUnitPrice());
			Product product = productDao.getProductByColorAndName(item
					.getProductName(), item.getProductColor());
			item.setProduct(product);
			item.setTotalMeter(total);
			item.setId(null);
			this.purchaseReturnItemDao.save(item);
		}
		PurchaseReturn tempPurchaseReturn = this.get(purchaseReturn.getId());
		tempPurchaseReturn.setMeterNum(meterNum);
		tempPurchaseReturn.setPiNum(piNum);
		tempPurchaseReturn.setMoneyNum(Double.valueOf(moneyNum).doubleValue());
		tempPurchaseReturn.setModifyTime(new Date());
		tempPurchaseReturn.setStatus(new Integer(1).shortValue());
		this.purchaseReturnDao.merge(tempPurchaseReturn);
		return true;
	}

	public boolean UpdateMemo(PurchaseReturn saleorder, String memo) {
		boolean result = false;
		PurchaseReturn tempPurchaseReturn = this.get(saleorder.getId());
		tempPurchaseReturn.setMemo(memo);
		this.purchaseReturnDao.merge(tempPurchaseReturn);
		return result;
	}

	public String isExistProduct(String productname, String color) {
		String result = "0";
		Product product = this.productDao.isExistSame(productname, color);
		if (product != null) {
			result = product.getId().toString();
		}
		return result;

	}

	/**
	 * 根据id获取销售订单及明细
	 * 
	 * @param id
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List getPurchaseReturnItemsById(Long id) {
		return purchaseReturnItemDao.getItemsByOrderId(id);
	}

	public boolean uppdatePurchaseReturn(PurchaseReturn purchaseReturn) {
		this.purchaseReturnDao.merge(purchaseReturn);
		return true;
	}

	/**
	 * 删除销售订单及明细
	 * 
	 * @param id
	 */
	public String deletePurchaseReturn(long id) {
		List<PurchaseReturnItem> items = this.purchaseReturnItemDao
				.getItemsByOrderId(id);
		PurchaseReturn purchaseReturn = purchaseReturnDao.get(id);
		boolean cancelflag = false;
		if (purchaseReturn != null) {
			if (purchaseReturn.getStatus() > 2) {
				cancelflag = true;
			}
			// cancelflag = (purchaseReturn.getStatus() ==
			// Short.valueOf(PurchaseReturn.order_staus_complete));
		}
		for (PurchaseReturnItem item : items) {
			item.setDeleted((short) 1);
			item.setModifyTime(new Date());
			if (cancelflag) {
				this.storageDao.cancelChargedStorageByFlowNo(purchaseReturn
						.getFlowNo());
			}
			this.purchaseReturnItemDao.getHibernateTemplate().update(item);

		}
		purchaseReturn.setDeleted((short) 1);
		purchaseReturn.setModifyTime(new Date());
		this.purchaseReturnDao.merge(purchaseReturn);
		// deleteDueFromAndSummary(purchaseReturn);
		return "success";
	}

	public String updatePurchaseReturnStatus(long id, int status,
			String responser) {
		PurchaseReturn order = this.get(id);
		int update = 3;
		int oldstatus = order.getStatus();
		if (oldstatus == 0) {
			update = 1;
		} else if (oldstatus == 1) {
			update = 2;
		} else if (oldstatus == 2) {
			update = 3;
		}

		order.setStatus(new Integer(update).shortValue());
		order.setModifyTime(new Date());
		order.setResponer(responser);
		this.purchaseReturnDao.getHibernateTemplate().update(order);
		return "success";
	}

	public String updatePurchaseReturnSend(long id, String responser) {
		PurchaseReturn order = this.get(id);
		order.setStatus(Short.parseShort("2"));
		order.setResponer(responser);
		order.setModifyTime(new Date());
		this.purchaseReturnDao.getHibernateTemplate().update(order);
		return "success";
	}

	public PurchaseReturn GetPurchaseReturnByid(long id) {
		PurchaseReturn order = this.purchaseReturnDao.getOrderByOrderId(id).get(0);
		return order;
	}

	public List GetPurchaseReturnListByid(long id) {
		return this.purchaseReturnDao.getOrderByOrderId(id);
	}

	@Override
	public PurchaseReturnDao getEntityDao() {
		return purchaseReturnDao;
	}

	public PurchaseReturnDao getPurchaseReturnDao() {
		return purchaseReturnDao;
	}

	public void setPurchaseReturnDao(PurchaseReturnDao purchaseReturnDao) {
		this.purchaseReturnDao = purchaseReturnDao;
	}

	public PurchaseReturnItemDao getPurchaseReturnItemDao() {
		return purchaseReturnItemDao;
	}

	public void setPurchaseReturnItemDao(
			PurchaseReturnItemDao purchaseReturnItemDao) {
		this.purchaseReturnItemDao = purchaseReturnItemDao;
	}

	public SupDao getSupDao() {
		return supDao;
	}

	public void setSupDao(SupDao supDao) {
		this.supDao = supDao;
	}

	public ProductDao getProductDao() {
		return productDao;
	}

	public void setProductDao(ProductDao productDao) {
		this.productDao = productDao;
	}

	public FlowNoDao getFlowNoDao() {
		return flowNoDao;
	}

	public void setFlowNoDao(FlowNoDao flowNoDao) {
		this.flowNoDao = flowNoDao;
	}

	public StaffDAO getStaffDao() {
		return staffDao;
	}

	public void setStaffDao(StaffDAO staffDao) {
		this.staffDao = staffDao;
	}

	public StorageDao getStorageDao() {
		return storageDao;
	}

	public void setStorageDao(StorageDao storageDao) {
		this.storageDao = storageDao;
	}

}
